#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@file_name: allowing_multiple_clients_to_connect.py
@date: 2025-07-29 12:10
@author: Falling Snow
@desc: 允许多个客户端连接.
"""
import socket

if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_address = ("127.0.0.1", 8000)
    server_socket.bind(server_address)
    server_socket.listen()

    connections: list[tuple] = []

    try:
        while True:
            connection, client_address = server_socket.accept()
            print(f"来自客户端{client_address}的连接")
            connections.append((connection, client_address))
            for con, caddr in connections:
                buffer = b""
                while buffer[-2:] != b"\r\n":
                    data = con.recv(2)
                    if not data:
                        break
                    else:
                        print(f"接受到了数据为: {data}")
                        buffer += data
                print(f"当前客户端{caddr}发送的所有数据为: {buffer[:-2].decode()}")
                con.sendall(buffer)
    finally:
        server_socket.close()
